package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addFriend(Long userId, Long targetuserId) {
        //给当前用户添加好友
        boolean exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(userId).and("friendId").is(targetuserId)), Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(userId);
            friend.setFriendId(targetuserId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //给用户的好友添加
        exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(targetuserId).and("friendId").is(userId)), Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(targetuserId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

    }

    @Override
    public PageResult<Friend> findContacts(Long userId, int page, int pagesize, String keyword) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count,pagesize,pages,page,list);
    }

    @Override
    public Friend findById(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(uid));
        return mongoTemplate.findOne(query, Friend.class);
    }

    @Override
    public void delete(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(uid));
        mongoTemplate.remove(query, Friend.class);
        query = new Query(Criteria.where("userId").is(uid).and("friendId").is(userId));
        mongoTemplate.remove(query, Friend.class);
    }
}
